//
//  SendBigDatasAction.swift
//  CarInf
//
//  Created by 方强 on 16/10/15.
//  Copyright © 2016年 MT. All rights reserved.
//

import UIKit
import CoreBluetooth

public class SendBigDatasAction: BLEBaseAction {
    private var datas:Data?;
    private var sendCharact:CBCharacteristic?;
    private var reviceCharact:CBCharacteristic?;
    
    public init(datas:Data, sendCharact:CBCharacteristic?, reviceCharact:CBCharacteristic?, option:BLEBaseAction_ActionOption){
        super.init(type: BLEBaseAction_ActionType.SENDBIGDATAS, option: option);
        self.datas = datas;
        self.sendCharact = sendCharact;
        self.reviceCharact = reviceCharact;
        
        checkDatas = 0;
        
        for b in datas {
            checkDatas = checkDatas &+ b;
        }

        blocks = datas.count / (option.getPerlenght()); // 计算一共有多少块
        if (datas.count % (option.getPerlenght()) != 0) {
            blocks += 1;
        }
    }
    
    // 提取分段后的数据
    public func getDatas() -> Data?{
        
        if(datas == nil){
            return nil;
        }
        
        let point = blocking * option.getPerlenght();
        if (point >= datas!.count) {
            return nil;
        }
        var getbyte:Data?;
        if ((option.getPerlenght() + point) > datas!.count) {
            getbyte = datas?.subdata(in: point ..< datas!.count);
        } else {
            getbyte = datas?.subdata(in: point ..< (point+option.getPerlenght()));
        }
        blocking += 1;
        return getbyte;
    }
    
    // 获取校验码
    private var checkDatas:UInt8 = 0;
    public func getCheckDatas() -> UInt8{
        return checkDatas;
    }
    
    // 获取校验码
    public static func getCheckDatasFromBytes(datas:Data) -> UInt8{

        var checkDatas:UInt8 = 0;
        for b in datas{
            checkDatas = checkDatas &+ b;
        }
        return checkDatas;
    }
    
    // 获取块大小
    private var blocks:Int = 0;
    private var blocking:Int = 0;
    public func getBlocks() -> Int{
        return blocks;
    }
    
    // 获取正在发送的指针
    public func getSendingIndex() -> Int{
    return blocking;
    }

    public var onSendProcess:((SendBigDatasAction, Int)->Void)?;
    
    public func getSendCharact() -> CBCharacteristic?{
        return sendCharact;
    }
    
    public func setSenddatasCharact(sendCharact:CBCharacteristic) {
        self.sendCharact = sendCharact;
    }
    
    public func getReviceCharact() -> CBCharacteristic?{
        return reviceCharact;
    }
    
    public func setRevicedatasCharact(reviceCharact:CBCharacteristic) {
        self.reviceCharact = reviceCharact;
    }
}
